package com.easygoods.controller;

import com.bestvike.stone.spring.controller.BaseController;
import com.bestvike.stone.spring.rest.common.CommonResponse;
import com.bestvike.stone.spring.shiro.SecurityUtils;
import com.bestvike.stone.spring.shiro.authc.AuthenticationToken;
import com.bestvike.stone.spring.shiro.authc.exception.account.AccountException;
import com.bestvike.stone.spring.shiro.authc.exception.credentials.CredentialsException;
import com.easygoods.enums.LoginUserType;
import com.easygoods.request.ExternalRegisterRequest;
import com.easygoods.request.SendRegisterSmsRequest;
import com.easygoods.response.LoginResponse;
import com.easygoods.service.AuthService;
import com.easygoods.service.SmsService;
import com.easygoods.shiro.auth.UserAuth;
import com.easygoods.shiro.token.ChannelToken;
import com.easygoods.shiro.token.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by 许崇雷 on 2018-12-25.
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController extends BaseController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private AuthService authService;

    //发送注册验证码
    @PostMapping("/sendRegisterSms")
    public CommonResponse<?> sendRegisterSms(@RequestBody SendRegisterSmsRequest request) {
        this.smsService.sendRegisterSms(request);
        return CommonResponse.success();
    }

    //三方注册
    @PostMapping("/external/register")
    public CommonResponse<?> register(@RequestBody ExternalRegisterRequest request) {
        this.authService.externalRegister(request);
        return CommonResponse.success();
    }

    //三方登录
    @PostMapping("/external/login")
    public CommonResponse<LoginResponse> loginExternal(@RequestBody ChannelToken token) {
        return this.loginCore(token);
    }

    //账号密码登录
    @PostMapping("/login")
    public CommonResponse<LoginResponse> login(@RequestBody UserToken token) {
        return this.loginCore(token);
    }

    //登录
    private CommonResponse<LoginResponse> loginCore(AuthenticationToken token) {
        try {
            final UserAuth userAuth = (UserAuth) SecurityUtils.login(token);
            return CommonResponse.success(userAuth.toResponse());
        } catch (AccountException e) {
            return CommonResponse.success(UserAuth.loginFail(LoginUserType.Unregistered).toResponse());
        } catch (CredentialsException e) {
            return CommonResponse.success(UserAuth.loginFail(LoginUserType.PwdError).toResponse());
        }
    }
}
